package com.minyifang.wcspf.work.ui.home.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpFragment;
import com.minyifang.wcspf.common.config.user.UserManager;
import com.minyifang.wcspf.common.md5.SafeUtils;
import com.minyifang.wcspf.common.utils.AnimUtils;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.adpter.MultiChooseAdapter;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.goods.activities.ConfirmOrderActivity;
import com.minyifang.wcspf.work.ui.goods.activities.ShoppingCartActivity;
import com.minyifang.wcspf.work.ui.home.activities.MainActivity;
import com.minyifang.wcspf.work.ui.home.fragments.interfaces.OnEditStateChangeListener;
import com.minyifang.wcspf.work.ui.home.model.AddToCarBean;
import com.minyifang.wcspf.work.ui.home.model.CalculateMoneyBean;
import com.minyifang.wcspf.work.ui.home.model.CarBean;
import com.minyifang.wcspf.work.ui.home.model.CarBeanObj;
import com.minyifang.wcspf.work.ui.home.presenter.HomePage3Presenter;
import com.minyifang.wcspf.work.ui.home.view.HomePage3View;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomePage3Fragment extends BaseMvpFragment<HomePage3View, HomePage3Presenter> implements HomePage3View, CompoundButton.OnCheckedChangeListener, OnEditStateChangeListener, SwipeMenuCreator, SwipeMenuItemClickListener {

    @BindView(R.id.ll_no_goods)
    LinearLayout ll_no_goods;
    @BindView(R.id.ll_have_goods)
    LinearLayout ll_have_goods;

    /*@BindView(R.id.ll_have_price_difference)
    LinearLayout ll_have_price_difference;
    @BindView(R.id.ll_no_price_difference)
    LinearLayout ll_no_price_difference;*/


    @BindView(R.id.tv_store_name)
    TextView tv_store_name;
    @BindView(R.id.rv_cart)
    SwipeMenuRecyclerView mSwipeMenuRecyclerView;
    @BindView(R.id.cb_select_all)
    CheckBox mCheckBox;
    @BindView(R.id.tv_toggle_edit_mode)
    TextView mTvToggleEditMode;

    @BindView(R.id.tv_tips)
    TextView tv_tips;
    @BindView(R.id.cb_songhuo)
    CheckBox cb_songhuo;
    @BindView(R.id.tv_total_money)
    TextView tv_total_money;
    @BindView(R.id.tv_operate)
    TextView tv_operate;

    private MultiChooseAdapter mMultiChooseAdapter;
    private List<CarBean> mList;

    private boolean isDel = false; //是否删除
    private String tipsMoney;  //满送金额
    private String totalMoney = "0";  //合计金额
    private String tipsNum;
    private ImageView mClickItemView;
    private ImageView mEndView;
    private AnimUtils mAnimUtils;
    private boolean mShowAnim;
    private AddToCartAdapter mAddToCartAdapter;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) activity;
            mEndView = mainActivity.findViewById(R.id.iv_car);
        }
    }

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_home_page3;
    }

    @OnClick(R.id.tv_toggle_edit_mode)
    void tv_toggle_edit_mode() {
        mMultiChooseAdapter.setEditMode(!mMultiChooseAdapter.isEditMode());
    }

    @Override
    protected void lazyLoadData() {

    }

    @Override
    protected void initView() {
        mAnimUtils = new AnimUtils(getContext());
        mList = new ArrayList<>();

        mMultiChooseAdapter = new MultiChooseAdapter(mList, getContext());

        mSwipeMenuRecyclerView.setSwipeMenuCreator(this);
        mSwipeMenuRecyclerView.setSwipeMenuItemClickListener(this);
        mSwipeMenuRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.custom_divider));
        mSwipeMenuRecyclerView.addItemDecoration(itemDecoration);
        mSwipeMenuRecyclerView.setAdapter(mMultiChooseAdapter);

        mCheckBox.setOnClickListener(v -> {
            mCheckBox.setChecked(mCheckBox.isChecked());
            if (mCheckBox.isChecked()) {
                mMultiChooseAdapter.selectedAll();
            } else {
                mMultiChooseAdapter.resetChoose();
            }

            calculateMoney();
        });
        mMultiChooseAdapter.setOnEditStateChangeListener(this);

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserManager.getInstance().isLogin()) {
            mCheckBox.setChecked(false);
            cb_songhuo.setChecked(false);
            getData();
        } else {
            ll_have_goods.setVisibility(View.GONE);
            ll_no_goods.setVisibility(View.VISIBLE);
            mTvToggleEditMode.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onVisibilityChanged(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            if (UserManager.getInstance().isLogin()) {
                mCheckBox.setChecked(false);
                getData();
            } else {
                ll_have_goods.setVisibility(View.GONE);
                ll_no_goods.setVisibility(View.VISIBLE);
                mTvToggleEditMode.setVisibility(View.GONE);
            }
        }
    }

    private void getData() {
        getPresenter().getCarData();
        //重置
        //reSet();
    }

    private void reSet() {
        tv_store_name.setText(UserManager.getInstance().getStoreName());
        tv_total_money.setText("0.00");
        tv_tips.setText(String.format("还差%s个品类和%s元，可享送货服务", tipsNum, tipsMoney));
        mTvToggleEditMode.setText("编辑");
        tv_operate.setText("结算");
        isDel = false;
        mMultiChooseAdapter.resetChoose();
        totalMoney = "0";
        /*ll_no_price_difference.setVisibility(View.GONE);
        ll_have_price_difference.setVisibility(View.VISIBLE);*/
        mCheckBox.setChecked(false);
        cb_songhuo.setChecked(false);
    }

    @OnClick({R.id.tv_coudan, R.id.tv_go_shopping})
    void couDan() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).checkMoudle(1);
        } else {
            startActivity(new Intent(getActivity(), MainActivity.class));
            LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(new Intent(MainActivity.BROADCAST_CHECK_CLASS));
        }
    }

    @Override
    protected HomePage3Presenter createPresenter() {
        return new HomePage3Presenter();
    }

    /**
     * 全选
     *
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mMultiChooseAdapter.selectedAll();
        } else {
            mMultiChooseAdapter.resetChoose();
        }

        calculateMoney();
    }

    @Override
    public void onEditStateChanged(boolean isEditMode) {
        if (isEditMode) {
            mTvToggleEditMode.setText("完成");
            tv_operate.setText("删除");
            isDel = true;
        } else {
            mTvToggleEditMode.setText("编辑");
            tv_operate.setText("结算");
            isDel = false;
        }
    }

    /**
     * 结算或删除
     */
    @OnClick(R.id.tv_operate)
    void tv_operate() {
        List<CarBean> selectList = new ArrayList<>();
        boolean hasSelect = false;
        String delString = "";
        for (int i = 0; i < mList.size(); i++) {
            CarBean carBean = mList.get(i);
            if (carBean.isSelect()) {
                delString += carBean.getComId() + ",";
                selectList.add(carBean);
                hasSelect = true;
            }
        }

        if (isDel) {
            if (delString.equals("")) {
                ToastHelper.getInstance(getContext()).showWarn("请勾选删除项");
                return;
            }
            LogUtil.e("删除id: " + delString.substring(0, delString.length() - 1));
            getPresenter().delCarGoods(delString.substring(0, delString.length() - 1));

        } else {

            if (hasSelect) {
                ConfirmOrderActivity.start(getActivity(), 1, tv_total_money.getText().toString(), selectList);
            } else
                ToastHelper.getInstance(getContext()).showWarn("请勾选商品");
        }
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
    }

    /**
     * 购物车数据
     *
     * @param respond
     */
    @Override
    public void showCarData(HttpRespond<String> respond) {
        reSet();
        mList.clear();
        if (respond.result == 1) {
            LogUtil.e("购物车数据: " + SafeUtils.decrypt(respond.data));
            CarBeanObj carBeanObj = new Gson().fromJson(SafeUtils.decrypt(respond.data), CarBeanObj.class);
            List<CarBean> list = carBeanObj.getComList();

            mList.addAll(list);
            tipsMoney = carBeanObj.getMuchMon();
            tipsNum = carBeanObj.getNumClass();
            tv_tips.setText(String.format("还差%s个品类和%s元，可享送货服务", carBeanObj.getNumClass(), carBeanObj.getMuchMon()));
        } else if (respond.result == -1) {
            Global.reLogin(getActivity());
        }
        //暂无数据
        mMultiChooseAdapter.notifyDataSetChanged();

        ll_have_goods.setVisibility(mList.size() > 0 ? View.VISIBLE : View.GONE);
        ll_no_goods.setVisibility(mList.size() > 0 ? View.GONE : View.VISIBLE);
        mTvToggleEditMode.setVisibility(mList.size() > 0 ? View.VISIBLE : View.GONE);
    }

    /**
     * 购物车数量加减回调
     *
     * @param respond
     */
    @Override
    public void showAddCarNumRes(HttpRespond<AddToCarBean> respond) {
        sendToUpdateCarNum();
        if (respond.result == 1) {
            AddToCarBean bean = respond.data;
            if (Integer.parseInt(bean.getQuantity()) <= 0) {
                getPresenter().getCarData();
                return;
            }

            try {
                mList.get(mFPos).getSkuMap().get(mCPos).setMscQuantity(bean.getQuantity());
                mAddToCartAdapter.notifyItemChanged(mCPos);
            } catch (Exception e) {
                e.printStackTrace();
//                getPresenter().getCarData();
            }
            calculateMoney();

            if (mShowAnim && !(getActivity() instanceof ShoppingCartActivity))
                mAnimUtils.startAnim(mClickItemView, mEndView);
        } else
            ToastHelper.getInstance(getContext()).showWarn(respond.message);
    }

    /**
     * 删除回调
     */
    @Override
    public void showDeleteRes(HttpRespond<String> respond) {
        sendToUpdateCarNum();
        if (respond.result == 1)
            getPresenter().getCarData();
    }

    private void sendToUpdateCarNum() {
        EventBus.getDefault().post(new RefreshEvent());
    }

    /**
     * 结算合计回调
     */
    @Override
    public void showCalculateMoney(HttpRespond<String> respond) {
        if (respond.result == 1) {
            if (respond.isaes == 1) {
                LogUtil.e(SafeUtils.decrypt(respond.data));
                CalculateMoneyBean calculateMoneyBean = new Gson().fromJson(SafeUtils.decrypt(respond.data), CalculateMoneyBean.class);
                tv_total_money.setText(calculateMoneyBean.getMoney());
                totalMoney = calculateMoneyBean.getMoney();
                if (calculateMoneyBean.getWayMode() == 1) { //有差价
                   /* ll_no_price_difference.setVisibility(View.GONE);
                    ll_have_price_difference.setVisibility(View.VISIBLE);*/
                    if (calculateMoneyBean.getNumDifference() < 1) {
                        tv_tips.setText(String.format("还差%s元，可享送货服务", calculateMoneyBean.getPriceDifference()));
                    } else if ("0.00".equals(calculateMoneyBean.getPriceDifference())) {
                        tv_tips.setText(String.format("还差%s个品类，可享送货服务", calculateMoneyBean.getNumDifference()));
                    } else
                        tv_tips.setText(String.format("还差%s个品类和%s元，可享送货服务", calculateMoneyBean.getNumDifference(), calculateMoneyBean.getPriceDifference()));
                } else {  //可送货上门
                   /* ll_no_price_difference.setVisibility(View.VISIBLE);
                    ll_have_price_difference.setVisibility(View.GONE);*/
                }
            }

        } else
            ToastHelper.getInstance(getContext()).showWarn(respond.message);
    }

    private int mFPos; //记录父层item的position
    private int mCPos; //记录子层item的position

    @Override
    public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
        int width = (int) getResources().getDimension(R.dimen.dp_70);
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                .setBackgroundColor(Color.parseColor("#83c120"))
                .setText("删除")
                .setTextSize(18)
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);
    }

    @Override
    public void onItemClick(SwipeMenuBridge menuBridge) {
        menuBridge.closeMenu();
        int position = menuBridge.getAdapterPosition();
        if (menuBridge.getDirection() == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
            //删除
            getPresenter().delCarGoods(mList.get(position).getComId());
        }
    }

    /**
     * 计算价格
     */
    private void calculateMoney() {
        if (isDel) {
            return;
        }
        String ids = "";
        boolean hasSelect = false;
        for (CarBean carBean : mList) {
            if (carBean.isSelect()) {
                hasSelect = true;
                for (CarBean.SkuMapBean skuMapBean : carBean.getSkuMap()) {
                    ids += skuMapBean.getMscId() + ",";
                }
            }
        }
        if (!hasSelect) {
            reSet();
            return;
        }
        LogUtil.e("计算价格id: " + ids.substring(0, ids.length() - 1));

        getPresenter().calculateMoney(ids.substring(0, ids.length() - 1), tipsMoney);
    }

    public class MultiChooseAdapter extends RecyclerView.Adapter<MultiChooseAdapter.Holder> {

        private List<CarBean> mBeanList;
        private Context mContext;
        private boolean mIsEditMode = false;

        private OnEditStateChangeListener mEditStateChangeListener;

        public MultiChooseAdapter(List<CarBean> stringList, Context context) {
            mBeanList = stringList;
            mContext = context;
        }


        public void setOnEditStateChangeListener(OnEditStateChangeListener editStateChangeListener) {
            mEditStateChangeListener = editStateChangeListener;
        }

        public boolean isEditMode() {
            return mIsEditMode;
        }

        public void setEditMode(boolean editMode) {
            if (mIsEditMode == editMode)
                return;
            mIsEditMode = editMode;
            notifyDataSetChanged();
            if (mEditStateChangeListener != null)
                mEditStateChangeListener.onEditStateChanged(mIsEditMode);
        }


        @SuppressLint("ClickableViewAccessibility")
        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View layout = LayoutInflater.from(mContext).inflate(R.layout.item_cart_goods_layout, parent, false);
            return new Holder(layout);
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            CarBean carBean = mBeanList.get(position);

            holder.item_isNew.setVisibility(carBean.getIsNew() == 1 ? View.VISIBLE : View.GONE);
            ImageUtils.getInstance().showImage( carBean.getDeputyPic(), holder.item_pic);
            holder.item_title.setText(carBean.getComName());


            List<CarBean.SkuMapBean> skuMap = carBean.getSkuMap();
            mAddToCartAdapter = new AddToCartAdapter(skuMap, holder);
            holder.mRvSpecification.setAdapter(mAddToCartAdapter);

            holder.mRvSpecification.setLayoutManager(new LinearLayoutManager(getContext()));

            holder.mIvMark.setOnClickListener(v -> {
                carBean.setSelect(!carBean.isSelect());
                notifyDataSetChanged();
                checkSelect();
                calculateMoney();
            });

            boolean isSelected = carBean.isSelect();
            if (isSelected) {
                holder.mIvMark.setImageResource(R.mipmap.ic_check_checked);
            } else {
                holder.mIvMark.setImageResource(R.mipmap.ic_check_normal);
            }
        }

        @Override
        public int getItemCount() {
            return mBeanList.size();
        }

        public void resetChoose() {
            changeAllSelectState(false);
        }

        public void selectedAll() {
            changeAllSelectState(true);
        }

        public void checkSelect() {
            boolean isAll = false;
            for (CarBean carBean : mBeanList) {
                if (carBean.isSelect())
                    isAll = true;
                else {
                    isAll = false;
                    break;
                }

            }
//            if (isAll)
            mCheckBox.setChecked(isAll);

        }

        /**
         * 改变所有item的选中状态
         *
         * @param state
         */
        private void changeAllSelectState(boolean state) {
            for (int i = 0; i < mBeanList.size(); i++) {
                mBeanList.get(i).setSelect(state);
            }
            notifyDataSetChanged();
        }

        class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.iv_mark)
            ImageView mIvMark;

            @BindView(R.id.item_isNew)
            FrameLayout item_isNew;
            @BindView(R.id.item_pic)
            ImageView item_pic;
            @BindView(R.id.item_title)
            TextView item_title;

            @BindView(R.id.rv_spec)
            RecyclerView mRvSpecification;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }


    public class AddToCartAdapter extends RecyclerView.Adapter<AddToCartAdapter.Holder> {
        private List<CarBean.SkuMapBean> mSkuList;
        private MultiChooseAdapter.Holder mHolder;

        public AddToCartAdapter(List<CarBean.SkuMapBean> skuMap, MultiChooseAdapter.Holder holder) {
            this.mSkuList = skuMap;
            this.mHolder = holder;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(getContext()).inflate(R.layout.item_cart_specification, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            CarBean.SkuMapBean bean = mSkuList.get(position);
            holder.item_price.setText(String.format("￥%s", bean.getPrice()));
            holder.item_specification.setText(String.format("(%s%s/%s)", bean.getSpQuantity(), bean.getComUnitName(), bean.getSkuUnitName()));
            holder.item_unit_price.setText(String.format("每%s￥%s元", bean.getComUnitName(), bean.getUnitPrice()));
            holder.edt_num.setText(bean.getMscQuantity());

            holder.edt_num.setOnFocusChangeListener((v, hasFocus) -> {
                LogUtil.e(position + "," + bean.getSkuId() + "," + hasFocus);
                if (!hasFocus) {
                    mFPos = mHolder.getAdapterPosition();
                    mCPos = position;
                    getPresenter().addCarNum(bean.getMscId(), holder.edt_num.getText().toString());
                    mClickItemView = mHolder.item_pic;
                    mShowAnim = true;
                }
            });

            holder.itemView.setOnClickListener(v -> holder.itemView.setFocusable(true));


            holder.plus.setOnClickListener(v -> {
                mFPos = mHolder.getAdapterPosition();
                mCPos = position;
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) + 1 + "");
                getPresenter().addCarNum(bean.getMscId(), holder.edt_num.getText().toString());
                mClickItemView = mHolder.item_pic;
                mShowAnim = true;
            });

            holder.reduce.setOnClickListener(v -> {
                mFPos = mHolder.getAdapterPosition();
                mCPos = position;
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) - 1 < 0 ? "0" : Integer.parseInt(holder.edt_num.getText().toString()) - 1 + "");
                getPresenter().addCarNum(bean.getMscId(), holder.edt_num.getText().toString());
                mShowAnim = false;
            });
        }

        @Override
        public int getItemCount() {
            return mSkuList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_price)
            TextView item_price;
            @BindView(R.id.item_specification)
            TextView item_specification;
            @BindView(R.id.item_unit_price)
            TextView item_unit_price;
            @BindView(R.id.iv_plus)
            ImageView plus;
            @BindView(R.id.iv_reduce)
            ImageView reduce;
            @BindView(R.id.item_num)
            EditText edt_num;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
